import Kangaroo from './kangaroo'


/**
 * 事件执行类
 *
 * @export
 * @class EventHandle
 */
export default class EventHandle {

  /**
   *
   * @type {Array<Function>}
   * @memberof EventHandle
   */
  funs: Array<Function> = []
  isEventOn = false
  /**
   * Creates an instance of EventHandle.
   * @param {Kangaroo} kangaroo
   * @param {string} evenType
   * @param {Function} [handler]
   * @memberof EventHandle
   */
  constructor(public kangaroo: Kangaroo, public evenType: string, public handler?: Function) {
    this.eventOn()
  }

  /**
   * 添加事件
   *
   * @memberof EventHandle
   */
  eventOn() {
    const _this = this
    this.funs = []
    this.handler = function (event: any) {
      _this.funs.forEach(val => {
        (function (func, evenType) {
          _this.kangaroo.actEvent = [evenType, func]
          func(event)
        })(val, _this.evenType)
      })
    }
    // const eventOn = this.kangaroo.eventOn
    _this.kangaroo.eventOn.call(_this.kangaroo.eventEnv, this.evenType, _this.handler, false, true)
    this.isEventOn = true
  }

  /**
   * 添加要执行的方法
   *
   * @param {Function} funs
   * @memberof EventHandle
   */
  add(funs: Function) {
    if (!this.isEventOn) this.eventOn()
    this.funs.push(funs)
  }

  /**
   * 移除事件
   *
   * @param {boolean} [compel] 是否强制移除
   * @memberof EventHandle
   */
  eventOff(compel?: boolean) {
    if (compel) this.funs = []
    else if (this.funs.length) return
    this.isEventOn = false
    // const eventOff = this.kangaroo.eventOff
    this.kangaroo.eventOff.call(this.kangaroo.eventEnv, this.evenType, this.handler)
  }

  /**
   * 移除执行的方法
   *
   * @param {Function} [funs]
   * @returns
   * @memberof EventHandle
   */
  destroy(funs?: Function | Array<Function>) {
    if (!funs) this.eventOff(true)
    if (typeof funs === 'function') funs = [funs]
    let isFilter
    this.funs = this.funs.filter(func => {
      isFilter = true
      for (let j = 0; j < funs.length; j++) {
        const _func = funs[j]
        if (_func === func) {
          isFilter = false
          break
        }
      }
      return isFilter
    })
    // for (let i = 0; i < this.funs.length; i++) {
    //   const func = this.funs[i]
    //   for (let j = 0; j < funs.length; j++) {
    //     const _func = funs[j]
    //     if (_func === func) {
    //       return this.funs.splice(i, 1)
    //     }
    //   }
    // }
    return this.eventOff()
  }
}
